package com.polukeuro.app.controllers;

import javax.jdo.PersistenceManager;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.polukeuro.app.model.manager.PMF;
import com.polukeuro.app.model.user.Gamer;

@Controller
@RequestMapping("/user")
public class UserController {

	private int getGamerData(Gamer g){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		int credit = 0;
		
		try{
			Gamer gStored = pm.getObjectById(Gamer.class,g.getId());
			if(gStored != null){
				g.setCredit(gStored.getCredit());
				g.setScore(gStored.getScore());
			}else{
				pm.makePersistent(g);
			}
		}finally{
			pm.close();
		}
		return credit;
	}
	
	
	@RequestMapping(method=RequestMethod.GET,value="gamer.json", headers="Accept=application/json")
	public Gamer getGamer(@PathVariable String requestUri){
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		Gamer gamer = new Gamer();
		if(user != null){
			gamer.setId(user.getUserId());
			gamer.setEmail(user.getEmail());
			gamer.setPseudo(user.getNickname());
			gamer.setLogged(true);
			gamer.setLogOutUrl(userService.createLogoutURL(requestUri));
			gamer.setCredit(this.getGamerData(gamer));
		}else{
			gamer.setLogIntUrl(userService.createLoginURL(requestUri));
		}
		return gamer;
	}
}
